import React, { useState, useEffect, useRef } from 'react'
import axios from '../../utils/axios'
import './index.scss'
import { message } from '../../components/message'
import { hex_md5 } from '../../utils/md5'
import { useHistory } from 'react-router-dom'
export default function Login() {
  let history = useHistory()
  const [mail, setMail] = useState('')
  const [code, setCode] = useState('')
  const [password, setPassword] = useState('')
  const [name, setName] = useState('')
  const [codeText, setCodeText] = useState(0)
  const [topColorRes, setTopColorRes] = useState('#5fabea')
  const [topColorLog, setTopColorLog] = useState('')
  const [type, setType] = useState('register')
  const [isLogin,setIsLogin] = useState(false)
  let timer = useRef()
  useEffect(() => {
    let isUnmounted = false
    // 清除定时器
    if (codeText <= 0) {
      clearInterval(timer.current)
       setCodeText(60)  
    }
    if (isLogin) {
      if (timer.current) clearTimeout(timer.current)
      // 防止在组件卸载后调用
      if (!isUnmounted) {
        timer.current = setTimeout(() => {
          history.replace('/home')
        }, 2000)
      }
    }
    return () => {
      isUnmounted = true
    }
  }, [codeText, isLogin])
  const submit = () => {
    if (timer.current) clearInterval(timer.current)
    console.log(codeText, 'codeText')
    axios.get('/login/getVerificationCode?mail=' + mail).then((res) => {
      message('发送成功')
      setCodeText(()=>(60))
      console.log(res)
      if (res.data.code === 0) {
        timer.current = setInterval(() => {
          if (codeText > 0) {
            setCodeText((codeText) => codeText - 1)
          } 
        }, 1000)
      } else if (res.data.code === 1) {
      }
    })
  }
  // 注册
  const toRegister = () => {
    //邮箱校验
    let email = mail.replace(/^\s+|\s+$/g, '').toLowerCase() //去除前后空格并转小写
    let mycode = code.replace(/^\s+|\s+$/g, '') //去除空格
    let mypassword = password.replace(/^\s+|\s+$/g, '')
    let reg = /^[a-z0-9](\w|\.|-)*@([a-z0-9]+-?[a-z0-9]+\.){1,3}[a-z]{2,4}$/i
    if (email.match(reg) !== null && mycode && mypassword.length >= 6 && name) {
      // 将密码加密后存到数据库,防止数据库泄露时密码泄露
      let data = {
        mail: mail,
        mycode: mycode,
        password: hex_md5(mypassword),
        name: name,
      }
      axios.post('/login/register', data).then((res) => {
        if (res.data.code !== 0) {
          message(res.data.data)
        } else {
          message('注册成功')
          setType('login')
          setTopColorLog('#5fabea')
        }
        // console.log(res)
      })
    } else {
      if (!name) {
        message('昵称不能为空')
      }
      if (!mypassword) {
        message('密码不能为空')
      } else if (mypassword.length < 6) {
        message('密码最少b为6位哦')
      }
      if (!mycode) {
        message('验证码不能为空')
      }
      if (email.match(reg) == null) {
        message('请填写正确的邮箱')
      }
    }

    return
  }
  // 登录
  const login = () => {
    let data = { mail: mail, password: hex_md5(password) }
    axios.post('/login/toLogin', data).then((res) => {
      // console.log(res)
      if (res.data.code !== 0) {
        message(res.data.data)
      } else {
        message('登录成功')
        setIsLogin(true)
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('userid', mail)
      }
    })
  }
  // 提交表单
  const handleSubmit = (e) => {
    e.preventDefault()
    // 去注册
    type === 'register' && toRegister()
    // 
    type ==='login' && login()

  }
  return (
    <div>
      <div className="login-mine">
        <div className="top">
          <div
            style={{ background: topColorRes }}
            onClick={() => {
              setTopColorRes('#5fabea')
              setTopColorLog('')
              setType('register')
            }}
          >
            注册
          </div>
          <div
            style={{ background: topColorLog }}
            onClick={() => {
              setTopColorLog('#5fabea')
              setTopColorRes('')
              setType('login')
            }}
          >
            登录
          </div>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="input-box">
            <span>邮 箱:</span>
            <input
              id="input"
              type="email"
              onChange={(e) => {
                setMail(e.target.value)
              }}
            ></input>
          </div>
          {type === 'register' ? (
            <div className="input-box">
              <span>验证码:</span>
              <input
                id="mycode"
                onChange={(e) => {
                  setCode(e.target.value)
                }}
              ></input>
              <button
                className={'get-code'}
                onClick={(e) => {
                  e.preventDefault()
                  submit()
                }}
                disabled={codeText!== 0 && codeText!==60}
                style={
                  codeText !== 60
                    ? {
                        background:
                          '-webkit-linear-gradient(to left, rgb(142, 158, 171), rgb(197, 204, 210))',
                      }
                    : {}
                }
              >
                {(codeText === 60 || codeText === 0)
                  ? '获取验证码'
                  : `${codeText}s后获取`}
              </button>
            </div>
          ) : (
            ''
          )}
          <div className="input-box">
            <span>密 码:</span>
            <input
              placeholder={type === 'register' ? '设置一个密码' : ''}
              id="pass"
              type="password"
              onChange={(e) => {
                setPassword(e.target.value)
              }}
            ></input>
          </div>
          {type === 'register' ? (
            <div className="input-box">
              <span>昵 称:</span>
              <input
                id="name"
                placeholder="设置一个昵称吧~"
                onChange={(e) => {
                  setName(e.target.value)
                }}
              ></input>
            </div>
          ) : (
            ''
          )}
          <div className={'btns'}>
            {type === 'register' ? (
              <input type="submit" className={'register'} value="注册" />
            ) : (
              ''
            )}
            {type === 'login' ? (
              <input className={'login'} type="submit" value="登录" />
            ) : (
              ''
            )}
          </div>
        </form>
      </div>
    </div>
  )
}
